<template>
  <div
    id="tags-view-container"
    @mouseenter="lockHeader"
    @mouseleave="unlockHeader"
    class="tags-view-container"
  >
    <scroll-pane
      ref="scrollPane"
      class="tags-view-wrapper"
      @scroll="handleScroll"
    >
      <router-link
        v-for="tag in visitedViews"
        ref="tag"
        :key="tag.fullPath"
        :style="isActive(tag) ? `color:${$store.state.app.themeColor}` : ''"
        :to="{ path: tag.fullPath }"
        tag="span"
        class="tags-view-item"
        @click.native="tagTo(tag)"
        @contextmenu.prevent.native="openMenu(tag, $event)"
      >
        <el-tag
          style="line-height: 28px; height: auto"
          :type="isActive(tag) ? 'primary' : 'info'"
          :closable="!isAffix(tag)"
          :disable-transitions="false"
          @close="closeSelectedTag(tag)"
        >
          {{
            $t(`index.${tag.title}`).indexOf('index.') === -1
              ? $t(`index.${tag.title}`)
              : tag.title
          }}
          <el-icon v-if="!isActive(tag)" :style="isActive(tag) ? `color:${$store.state.app.themeColor}` : ''"><Location /></el-icon>
          <el-icon v-else :style="isActive(tag) ? `color:${$store.state.app.themeColor}` : ''"><LocationFilled /></el-icon>
        </el-tag>
      </router-link>
    </scroll-pane>
    <div class="close-all-tag">
      <!--      // 关闭全部按钮-->
      <el-button
        class="close-button-wrap"
        type="primary"
        size="mini"
        @click="closeAllTags(selectedTag)"
        >{{ $t('index.close') }}</el-button
      >
      <!--      返回顶部 折叠导航按钮组-->
      <div style="width: 20px; height: 100%; margin-top: 20px">
        <el-tooltip placement="left">
          <div
            slot="content"
            class="dintl-el-tooltip-wrap"
            style="color: orange; font-weight: 300"
          >
            Show or hide the navigation bar
          </div>
          <div
            class="button-group-wrap"
            :style="{
              color: 'orange',
              marginTop: '-5px',
              marginBottom: '5px',
            }"
            @click="handleHeaderCollapse"
          >
            <i class="el-icon-orange" />
          </div>
        </el-tooltip>
        <el-tooltip placement="left">
          <div
            slot="content"
            class="dintl-el-tooltip-wrap"
            :style="{
              color: $store.state.app.themeColor,
              fontWeight: '300',
            }"
          >
            Back to top
          </div>
          <div
            class="button-group-wrap"
            :style="{
              color: $store.state.app.themeColor,
            }"
            @click="backTop"
          >
            <i class="el-icon-upload2" />
          </div>
        </el-tooltip>
      </div>
    </div>
    <ul
      v-show="visible"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="refreshSelectedTag(selectedTag)">Refresh</li>
      <li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">
        Close
      </li>
      <li @click="closeOthersTags">Close Others</li>
      <li @click="closeAllTags(selectedTag)">Close All</li>
    </ul>
  </div>
</template>

<script>
import ScrollPane from './ScrollPane.vue'
import path from 'path-browserify'
import { getLocal, removeLocal, setLocal } from '@/utils/navigation'

export default {
  components: { ScrollPane },
  data() {
    return {
      visible: false,
      top: 0,
      left: 0,
      selectedTag: {},
      affixTags: [],
    }
  },
  computed: {
    visitedViews() {
      console.log(this.$store.state.tagsView.visitedViews)
      return this.$store.state.tagsView.visitedViews
    },
  },
  watch: {
    $route: {
      handler() {
        this.addTags()
        this.moveToCurrentTag()
      },
      deep: true,
    },
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    },
    '$store.state.tagsView.visitedViews': function (val) {
      // 将tagsView的标签缓存到localStorage
      let tagViewHistory = JSON.stringify(val, [
        'fullPath',
        'meta',
        'name',
        'path',
        'title',
        'affix',
      ])
      setLocal('tagViewHistory', tagViewHistory)
    },
    '$store.state.tagsView.currentView': function (val) {
      let tagViewCurrent = JSON.stringify(val, [
        'fullPath',
        'meta',
        'name',
        'path',
        'title',
        'affix',
        'query',
      ])
      setLocal('tagViewCurrent', tagViewCurrent)
    },
  },
  mounted() {
    let version = getLocal('app-version')
    if (version !== '4.0.0') {
      removeLocal('tagViewHistory')
      removeLocal('tagViewCurrent')
      removeLocal('featureManagerColumn')
      removeLocal('realTimeTableColumn')
      removeLocal('offlineTableColumn')
      removeLocal('dintTheme')
      removeLocal('--primary')
      setLocal('app-version', '4.0.0')
      this.$router.go(0)
    }
    // 初始化tagViews
    let isHaveCache = getLocal('tagViewHistory')
    try {
      this.setTagViews()
      this.initTags()
      this.addTags()
    } catch {
      this.initTags()
      this.addTags()
    }
    this.$nextTick(() => {
      this.moveToCurrentTag()
    })
  },
  methods: {
    backTop() {
      // 回到顶部事件
      let dot = document.getElementsByClassName('page-content')[0]
      dot.scroll({
        top: 0,
        left: 0,
        behavior: 'smooth',
      })
      // this.$store.commit('setIsShowHeader', true)
    },
    handleHeaderCollapse() {
      // 折叠导航栏
      console.log('---')
      if (this.$store.state.app.isShowHeader) {
        this.$store.commit('setIsShowHeader', false)
      } else {
        this.$store.commit('setIsShowHeader', true)
      }
    },
    setTagViews() {
      let tagViewHistory = JSON.parse(getLocal('tagViewHistory'))
      let tagViewCurrent = JSON.parse(getLocal('tagViewCurrent'))
      this.$store.commit('tagsView/RECOVERY_VISITED', tagViewHistory)
      this.$store.commit('tagsView/RECOVERY_CURRENT', tagViewCurrent)
    },
    tagTo(tag) {
      if (tag.name.indexOf('link2Frame') > -1) {
        debugger
        this.$store.commit('tagsView/SET_CURRENT_VIEW', tag)
      } else {
        this.$store.commit('tagsView/SET_CURRENT_VIEW', tag)
      }
    },
    lockHeader() {
      this.$store.commit('setIsLockHeader', true)
    },
    unlockHeader() {
      this.$store.commit('setIsLockHeader', false)
    },
    isActive(route) {
      // this.$store.dispatch('tagsView/updateVisitedView', this.$route)
      if (route.name === 'PipelineView' || route.name === 'PipelineEdit') {
        return (
          route.fullPath === this.$store.state.tagsView.currentView.fullPath
        )
      } else {
        return route.name === this.$store.state.tagsView.currentView.name
      }
    },
    isAffix(tag) {
      return tag.meta && tag.meta.affix
    },
    filterAffixTags(routes, basePath = '/') {
      let tags = []
      routes.forEach((route) => {
        if (route.meta && route.meta.affix === true) {
          const tagPath = path.resolve(basePath, route.path)
          tags.push({
            fullPath: tagPath,
            path: tagPath,
            name: route.name,
            meta: { ...route.meta },
          })
        }
        if (route.children) {
          const tempTags = this.filterAffixTags(route.children, route.path)
          if (tempTags.length >= 1) {
            tags = [...tags, ...tempTags]
          }
        }
      })
      return tags
    },
    initTags() {
      const affixTags = (this.affixTags = this.filterAffixTags(
        this.$router.options.routes
      ))
      for (const tag of affixTags) {
        // Must have tag name
        if (tag.name) {
          this.$store.dispatch('tagsView/addVisitedView', tag)
        }
      }
    },
    addTags() {
      const { name } = this.$route
      if (name) {
        this.$store.dispatch('tagsView/addView', this.$route)
      }
      return false
    },
    moveToCurrentTag() {
      const tags = this.$refs.tag
      this.$nextTick(() => {
        for (const tag of tags) {
          if (this.$route.fullPath.indexOf(tag.to.path) > -1) {
            this.$refs.scrollPane.moveToTarget(tag)
            // when query is different then update
            // if (tag.to.fullPath !== this.$route.fullPath) {
            //   this.$store.dispatch('tagsView/updateVisitedView', this.$route)
            // }
            break
          }
        }
      })
    },
    refreshSelectedTag(view) {
      this.$store.dispatch('tagsView/delCachedView', view).then(() => {
        const { fullPath } = view
        this.$nextTick(() => {
          this.$router.go(0)
        })
      })
    },
    closeSelectedTag(view) {
      this.$store
        .dispatch('tagsView/delView', view)
        .then(({ visitedViews }) => {
          if (this.isActive(view)) {
            this.toLastView(visitedViews, view)
          }
        })
    },
    closeOthersTags() {
      this.$router.push(this.selectedTag)
      this.$store
        .dispatch('tagsView/delOthersViews', this.selectedTag)
        .then(() => {
          this.moveToCurrentTag()
        })
    },
    closeAllTags(view) {
      this.$store.dispatch('tagsView/delAllViews').then(({ visitedViews }) => {
        if (this.affixTags.some((tag) => tag.path === view.path)) {
          return
        }
        this.toLastView(visitedViews, view)
      })
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        this.$router.push({
          path: latestView.fullPath,
        })
      } else {
        // now the default is to redirect to the home page if there is no tags-view,
        // you can adjust it according to your needs.
        if (view.name === 'Dashboard') {
          // to reload home page
          this.$router.replace({ path: '/redirect' + view.fullPath })
        } else {
          this.$router.push('/')
        }
      }
    },
    openMenu(tag, e) {
      const menuMinWidth = 105
      const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
      const offsetWidth = this.$el.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft + 15 // 15: margin right

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }
      let topMinor = this.$store.state.app.isShowHeader ? 50 : 0
      this.top = e.clientY - topMinor
      this.visible = true
      this.selectedTag = tag
    },
    closeMenu() {
      this.visible = false
    },
    handleScroll() {
      this.closeMenu()
    },
  },
}
</script>

<style lang="less" scoped>
.tags-view-wrapper {
  .tags-view-item {
    .el-icon-close {
      cursor: pointer;
      height: 15px;
      font-size: 15px;
      width: 15px;
      line-height: 9px;
      vertical-align: 1px;
      border-radius: 50%;
      text-align: center;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      transform-origin: 100% 50%;
      &:before {
        transform: scale(0.6);
        display: inline-block;
        vertical-align: -3px;
      }
      &:hover {
        background-color: #b4bccc;
        color: #fff;
      }
    }
  }
}
.tags-view-container {
  user-select: none;
  height: 50px;
  line-height: 50px;
  width: 100%;
  overflow: hidden;
  //position: absolute;
  display: inline-block;
  background: #fff;
  border-bottom: 1px solid #d8dce5;
  box-shadow: -3px 0 10px 3px rgba(0, 0, 0, 0.1);
  .tags-view-wrapper {
    .tags-view-item {
      cursor: pointer;
      display: inline-block;
      position: relative;
      height: 26px;
      line-height: 26px;
      color: #495060;
      background: transparent;
      padding: 0 6px;
      font-size: 12px;
      margin-top: 4px;
      &:first-of-type {
        margin-left: 15px;
      }
      &:last-of-type {
        margin-right: 15px;
      }
    }
  }
  .close-all-tag {
    display: flex;
    align-content: center;
    justify-content: flex-start;
    align-items: center;
    background: white;
    float: right;
    right: 0;
    top: 0;
    //line-height: 50px;
    text-align: left;
    width: 110px;
    height: 50px;
    border-bottom: none;
    box-shadow: -3px 0 10px 3px rgba(0, 0, 0, 0.1);
    z-index: 10;
    .close-button-wrap {
      width: 80px;
      height: fit-content;
      margin-left: 10px;
    }
    .button-group-wrap {
      font-size: 16px;
      padding: 0;
      text-align: center;
      height: 15px;
      width: 20px;
      line-height: 1;
      cursor: pointer;
      transition-duration: 0.3s;
      opacity: 0.7;
    }
    .button-group-wrap:hover {
      opacity: 1;
      transform: scale(1.2);
    }
  }
  .contextmenu {
    margin: 0;
    line-height: 1;
    background: #fff;
    z-index: 3000;
    position: absolute;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 400;
    color: #333;
    box-shadow: 0 2px 15px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    li {
      margin: 0;
      padding: 7px 16px;
      cursor: pointer;
      &:hover {
        background: #eee;
      }
    }
  }
}
</style>
